package com.wlyy.starter.mybatis.expand;

import com.baomidou.mybatisplus.core.injector.AbstractMethod;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.wlyy.starter.mybatis.SQLUtil;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlSource;

/**
 * 批量写,没有字段排除策略
 * <p>
 * <code>
 * INSERT INTO %s (%s) VALUES <foreach collection="list" item="et" separator=","> (%s) </foreach>
 * </code>
 * </p>
 */
public class InsertBatch extends AbstractMethod {

    public final static String METHOD_ID = "insertBatch";

    public InsertBatch(String name) {
        super(name);
    }

    @Override
    public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) {

        final String sqlTemp = "<script>INSERT INTO %s (%s) VALUES <foreach collection=\"" + COLLECTION + "\" item=\"" + ENTITY + "\" separator=\",\"> (%s) </foreach></script>";
        final String tableName = tableInfo.getTableName();
        final String columnSql = SQLUtil.getAllColumn(tableInfo);
        final String valueSql = SQLUtil.getAllField(tableInfo, ENTITY_DOT);
        final String sql = String.format(sqlTemp, tableName, columnSql, valueSql);
        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, modelClass);
        return this.addInsertMappedStatement(mapperClass, modelClass, METHOD_ID, sqlSource,
                NoKeyGenerator.INSTANCE, tableInfo.getKeyProperty(), tableInfo.getKeyColumn());
    }
}
